import Vector2 from "../vector";

export class BoardCell {
  pos = Vector2.Zero;
  val: number;
  obj: any;

  static readonly Empty = new BoardCell(0, null) as Readonly<BoardCell>;

  constructor(val: number, obj: any) {
    this.val = val;
    this.obj = obj;
  }
}

export default class Board {
  // 网格的行数和列数
  readonly rows;
  readonly cols;
  // 网格状态
  private grid:BoardCell[][] = [];

  constructor(rows: number, cols: number) {
    this.rows = rows;
    this.cols = cols;

    // 初始化网格
    for (let r = 0; r < rows; r++) {
      this.grid[r] = [];
      for (let c = 0; c < cols; c++) {
        this.grid[r][c] = BoardCell.Empty;
      }
    }
  }

  toString() {
    let lines = '';
    for (let r = 0; r < this.rows; r++) {
      for (let c = 0; c < this.cols; c++) {
        const cell = this.grid[r][c];
        lines += cell.val == 0 ? '*' : cell.val;
      }
      lines += '\n';
    }
    return lines;
  }

  setCell(gridX: number, gridY: number, cell: BoardCell) {
    if (cell != BoardCell.Empty) {
      cell.pos.x = gridX;
      cell.pos.y = gridY;
    }
    this.grid[gridY][gridX] = cell;
  }

  isSpace(gridX: number, gridY: number) {
    return this.isBoundPos(gridX, gridY) && this.get(gridX, gridY).val == 0;
  }

  get(gridX: number, gridY: number) {
    return this.grid[gridY][gridX];
  }

  find(equal: (cell: BoardCell) => boolean, startX = 0, startY = 0) {
    for (let r = startY; r < this.rows; r++) {
      for (let c = startX; c < this.cols; c++) {
        if (equal(this.grid[r][c])) {
          return this.grid[r][c];
        }
      }
    }
    return null;
  }

  isBoundPos(gridX: number, gridY: number) {
    return 0 <= gridX && gridX < this.cols && 0 <= gridY && gridY < this.rows;
  }

  isFloorPos(gridY: number) {
    return gridY + 1 == this.rows - 1;
  }
}